<template>
	<div v-waterMarker class="merak-float" v-loading="loading">
		<div class="header">
			<div class="leftTitle">
				<!-- <div class="icon" @click="emit('close',state.refresh,props.typeId)">
					<el-icon size="20">
						<ArrowLeft />
					</el-icon>
				</div> -->
				<div class="title">{{$t("goods_allocation_merge.add_merge")}}</div>
			</div>
			<div class="btnBoxs">
				<el-button plain @click="emit('close',state.refresh,props.typeId)">{{$t('merak.cancel')}}</el-button>
				<el-button type="primary" plain
					@click="submitForm(ruleFormRef,true)">{{ $t("merak.save_continue") }}</el-button>
				<el-button type="primary" @click="submitForm(ruleFormRef,false)">{{ $t("merak.save") }}</el-button>
				<div class="icon" @click="emit('close',state.refresh,props.typeId)">
					<el-icon size="20">
						<Close />
					</el-icon>
				</div>
			</div>
		</div>
		<div class="content">
			<div class="merak-float-overflow-y">
				<el-form ref="ruleFormRef" labelPosition="top" :model="ruleForm" :rules="rules">
					<div class="group">
						<div class="titleHeader" @click="state.basicsMsg = !state.basicsMsg">
							<el-icon size="16" v-if="state.basicsMsg">
								<CaretRight />
							</el-icon>
							<el-icon size="16" v-else>
								<CaretBottom />
							</el-icon>
							<div class="group-title">{{$t("goods_allocation_merge.merge_attribute")}}</div>
						</div>
						<el-row :gutter="40" v-if="!state.basicsMsg">
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.type_id')" prop="type_id">
									<el-select filterable class="qf_select" :placeholder="$t('merak.placeholder_select')" v-model="ruleForm.type_id" @change="value=>getAttributeFun(value)">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.goodsTypeArr" :key="item?.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_allocation_merge.merge_prop_ru')" prop="merge_prop_ru" :error="newRules.merge_prop_ru">
									<el-input :maxlength="100" class="qf_input" type="text" v-model="ruleForm.merge_prop_ru"/>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_allocation_merge.merge_prop_cn')" prop="merge_prop_cn" :error="newRules.merge_prop_cn">
									<el-input :maxlength="50" class="qf_input" type="text" v-model="ruleForm.merge_prop_cn" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_allocation_merge.merge_prop_en')" prop="merge_prop_en" :error="newRules.merge_prop_en">
									<el-input :maxlength="50" class="qf_input" type="text" v-model="ruleForm.merge_prop_en">
										<template #prefix>merge_</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.property_sale')" prop="qifa_prop_id">
									<el-select class="qf_select" filterable :placeholder="$t('merak.placeholder_select')" v-model="ruleForm.qifa_prop_id" @change="value=>showCC(value)">
										<el-option :label="item?.label" :value="item?.value"
											v-for="item in opstionsObjs?.qifaPropType" :key="item?.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="$t('goods_attribute.property_clearance')" prop="cc_prop_id">
									<el-select class="qf_select" filterable :placeholder="$t('merak.placeholder_select')" v-model="ruleForm.cc_prop_id" @change="showTable">
										<el-option :label="item?.label" :value="item?.value" 
											v-for="item in opstionsObjs?.ccPropType" :key="item?.value"/>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</div>
					<div class="group" :class="state.propertyList?'':'group-table'" v-if="isShowTable">
						<div class="group-head">
							<div class="titleHeader" @click="state.propertyList = !state.propertyList">
								<el-icon size="16" v-if="state.propertyList">
									<CaretRight />
								</el-icon>
								<el-icon size="16" v-else>
									<CaretBottom />
								</el-icon>
								<div class="group-title">{{$t('goods_allocation_merge.merge_attribute_value_list')}}</div>
							</div>
							<div class="btnBox">
								<el-button type="primary" plain @click="addRows">{{$t('goods_allocation_merge.add_merge_enumeration_value')}}</el-button>
							</div>
						</div>
						<div class="float-table-row" v-if="!state.propertyList">
							<div class="table-box">
								<basicTableSum ref="editTableRef" v-bind="tableConfig" @editFormFun="editFormClick" >
									<template #qifa_propvalue_id="{ scope }">
										<el-select
											filterable
											v-model="(scope as Record<string, any>).qifa_propvalue_id.value"
											@change="value=>selectQifaPropvalueFun(scope,value)"
										>
										  <el-option v-for="option in opstionsObjs.qifaPropval" :value="option.value" :label="option.label" />
										</el-select>
									</template>
									<template #cc_propvalue_id="{ scope }">
										<el-select
											filterable
											v-model="(scope as Record<string, any>).cc_propvalue_id.value"
											@change="value=>selectCcPropvalueFun(scope,value)"
										>
										  <el-option v-for="option in opstionsObjs.ccPropval" :value="option.value" :label="option.label" />
										</el-select>
									</template>
									<template #handle="{ row }">

										<el-button type="danger" link @click="delFun(row)">{{$t('merak.delete')}}</el-button>

									</template>
								</basicTableSum>
							</div>
						</div>
					</div>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import type { FormInstance, FormRules, } from "element-plus";
	import { getCurrentInstance, ref, reactive, computed, watch, onMounted,nextTick } from "vue";
	import basicTableSum from "@/components/MerakEditTable/components/basicTable/moreEdit.vue";
	import { initAttribute, getAttribute,getPropval,setMergeAttribute } from "@/api/modules/goodsArchive/mergeAttribute";
	import { failMsg,successMsg } from "@/utils/messageUtils";
	const { proxy } = getCurrentInstance()!;
	const props = defineProps<{
		typeId?:string|number;
	}>();
	const ruleFormRef = ref<FormInstance>()
	const editTableRef = ref<FormInstance>()
	const loading = ref(true);
	const ruleForm = reactive({
		"type_id": "",//商品类型
		"merge_prop_ru": "",//合并属性名称(俄文)
		"merge_prop_cn": "",//合并属性名称(中文)
		"merge_prop_en": "",//合并属性名称(英文)
		"qifa_prop_id": "",//企发属性
		"cc_prop_id": "",//清关属性
	})
	//页面的select下拉数据
	const opstionsObjs = reactive({
		goodsTypeArr: [],//商品类型
		qifaPropType: [],//企发属性类型
		ccPropType: [],//清关属性类型
		ccInitPropType:[],//清关原始数据
		qifaPropval:[],//企发销售枚举值
		ccPropval:[],//企发销售枚举值
		
	})
	const newRules = reactive<FormRules<RuleForm>>({})
	const validateInput = (rule, value, callback) => {
	  const regexPattern = /^[a-z][a-z0-9_]*$/;
	  if (!value || !regexPattern.test(value)) {
	    return callback(new Error(proxy!.$t("goods_attribute.input_error")));
	  }
	  callback();
	};
	const rules = reactive<FormRules<RuleForm>>({
		type_id: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'change',
			},
		],
		merge_prop_ru: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
		merge_prop_cn: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
		merge_prop_en: [
			{
				validator: validateInput, 
				trigger: 'blur' ,
			},
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'blur',
			},
		],
		qifa_prop_id: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'change',
			},
		],
		cc_prop_id: [
			{
				required: true,
				message: proxy!.$t("goods_attribute.require"),
				trigger: 'change',
			},
		],
	})
	const emit = defineEmits<{
		close : [refresh: boolean,typeId:string|number];
	}>();

	const state = reactive<{
		refresh : boolean;
		basicsMsg : boolean;
		propertyList : boolean;

	}>({
		refresh: false,
		basicsMsg: false,
		propertyList: false,
	});

	const selectQifaPropvalueFun = (scoped,e) => {
		editTableRef.value?.ininBaseInfo();
		let tLabel = opstionsObjs.qifaPropval.find(option => option.value === e)
		qifaPropvalueId.value = tLabel.label;
		tableConfig.tableData[scoped.index].qifa_propvalue_id = {
			label:tLabel.label,
			value:tLabel.value,
		}
		let cLabel = opstionsObjs.ccPropval.find(option => option.value === tLabel)
		if(cLabel != undefined){
			ccPropvalueId.value = cLabel.label;
			tableConfig.tableData[scoped.index].cc_propvalue_id = {
				label:cLabel.label,
				value:cLabel.value,
			}
		}
	}
	const selectCcPropvalueFun = (scoped,e) => {
		editTableRef.value?.ininBaseInfo();
		let cLabel = opstionsObjs.ccPropval.find(option => option.value === e)
		ccPropvalueId.value = cLabel.label
		tableConfig.tableData[scoped.index].cc_propvalue_id = {
			label:cLabel.label,
			value:cLabel.value,
		}
	}
	
	const addRows = () => {
		editStatusType.value = "add";
		let obj = {
			merge_propvalue_ru: {//合并属性值(俄文)
				label: "",
				value: "",
			},
			merge_propvalue_cn: {//合并属性值(中文)
				label: "",
				value: ""
			},
			qifa_propvalue_id: {//企发枚举值
				label: "",
				value: ""
			},
			cc_propvalue_id: {//清关枚举值
				label: "",
				value: ""
			},
			sort: {//排序
				label: "",
				value: ""
			},
		};
		tableData.value.push(obj);
		nextTick(()=>{
			editTableRef.value.initBottomScroll()
		})
	}
	const tableHeadData = reactive([]);
	const tableData = ref([]);
	const headConfig = reactive({});//头部配置是否可编辑 
	const editStatusType = ref("");
	const qifaPropvalueId  = ref("");//企发销售枚举选中值
	const ccPropvalueId  = ref("");//清关枚举选中值
	const tableConfig = reactive<{
		headData : [];
		tableData : [];
		headConfig : [];
	}>({
		headData: tableHeadData,//表格头部数据   必须值
		tableData: tableData,//表格内容数据      必须值
		headConfig: headConfig,//可编辑列类型    必须值 
	})

	//获取初始化数据
	const initMsg = () => {
		let data = {}; 
		initAttribute().then(({ code, data }) => {
			if (code == 2000) {
				
				opstionsObjs.goodsTypeArr = data.dataarr.type_id;//商品类型
				
				if(props.typeId != "" && props.typeId != undefined && props.typeId != "all" && props.typeId != -1){
					ruleForm.type_id = Number(props.typeId);
					getAttributeFun(Number(props.typeId))
				}
				setTimeout(()=>{
					loading.value = false;
				},0)
			}
		})
	}
	
	//获取企发销售属性和清关销售属性
	const getAttributeFun = (e) =>{
		let data = {	
			type_id:e,
		};
		getAttribute(data).then(({ code, data }) => {
			if (code == 2000) {
				opstionsObjs.qifaPropType = data.prop;
				opstionsObjs.ccPropType = data.cc_prop;
				opstionsObjs.ccInitPropType = data.cc_prop;
			}
		})
	}
	const isShowTable = ref(false);
	const showTable= (e) => {
		getPropvalFunTwo(ruleForm.qifa_prop_id,e,ruleForm.type_id)
		//const typeItem = opstionsObjs.ccInitPropType.find(item=>item.value == e);
		
	}
	//获取企发销售枚举值和清关枚举值
	const getPropvalFun = (pid,cid,tid) =>{
		let data = {
			prop_id:pid,
			cc_prop_id:cid,
			type_id:tid
		};
		getPropval(data).then(({ code, data }) => {
			if (code == 2000) {
				opstionsObjs.qifaPropval = data.propval;
				data.propval.map(item=>{
					let obj = {
						merge_propvalue_ru: {//合并属性值(俄文)
							label: item.name_ru,
							value: item.name_ru,
						},
						merge_propvalue_cn: {//合并属性值(中文)
							label: item.name_cn,
							value: item.name_cn
						},
						qifa_propvalue_id: {//企发枚举值
							label: item.label,
							value: item.value
						},
						cc_propvalue_id: {//清关枚举值
							label: "",
							value: ""
						},
						sort: {//排序
							label: "",
							value: ""
						},
					};
					tableData.value.push(obj);
				})
			}
		})
	}
	const getPropvalFunTwo = (pid,cid,tid) =>{
		let data = {
			prop_id:pid,
			cc_prop_id:cid,
			type_id:tid
		};
		getPropval(data).then(({ code, data }) => {
			if (code == 2000) {
				opstionsObjs.ccPropval = data.cc_propval;
			}
		})
	}
	const showCC = (e) => {
		const typeItem = opstionsObjs.qifaPropType.find(item=>item.value == e);
		if(typeItem != -1){
			let newArr = opstionsObjs.ccInitPropType;
			let screenArr = newArr.filter(option=>option.prop_type == typeItem.prop_type)
			opstionsObjs.ccPropType = screenArr;
			ruleForm.cc_prop_id = "";
			if(typeItem.prop_type == 1){
				isShowTable.value = true;
				getPropvalFun(ruleForm.qifa_prop_id,"",ruleForm.type_id)
			} else {
				isShowTable.value = false;
			}
		}
		
	}
	const delFun = (e) => {
		tableConfig.tableData.splice(e.index, 1);
	}
	const editFormClick = (e) => {
		const idx = e.index;
		const editItem = {};
		Object.assign(editItem, e);
		delete editItem["index"];
		tableConfig.tableData[idx] = editItem;
	}

	const hasDuplicates = (arr) => {
	  const paramPairs = new Set();
	  for (const obj of arr) {
	    const pair = obj.qifa_propvalue_id + '|' + obj.cc_propvalue_id;
	    if (paramPairs.has(pair)) {
	      return true;
	    }
	    paramPairs.add(pair);
	  }
	  return false;
	};
	const hasRU = (arr) => {
	  const paramPairs = new Set();
	  for (const obj of arr) {
	    const pair = obj.merge_propvalue_ru;
	    if (paramPairs.has(pair)) {
	      return true;
	    }
	    paramPairs.add(pair);
	  }
	  return false;
	};
	const hasCN = (arr) => {
	  const paramPairs = new Set();
	  for (const obj of arr) {
	    const pair = obj.merge_propvalue_cn;
	    if (paramPairs.has(pair)) {
	      return true;
	    }
	    paramPairs.add(pair);
	  }
	  return false;
	};
	//接口返回报错信息
	const handleValidEditTable = (tableDataArr: any) => {
		let isError = false;
		for(let i = 0;i<tableDataArr.length;i++){
			let titem = tableDataArr[i];
			const excludeTableData = tableConfig.tableData.filter((_, index) => index !== i);
			if(titem.merge_propvalue_ru == "" || titem.merge_propvalue_cn == "" || titem.qifa_propvalue_id == "" || titem.cc_propvalue_id == ""){
				if(titem.merge_propvalue_ru == ""){
					tableConfig.tableData[i].merge_propvalue_ru.errTip = proxy!.$t("goods_attribute.merge_error")
					isError = true
				}
				if(titem.merge_propvalue_cn == ""){
					tableConfig.tableData[i].merge_propvalue_cn.errTip = proxy!.$t("goods_attribute.merge_error")
					isError = true
				}
				if(titem.qifa_propvalue_id == ""){
					tableConfig.tableData[i].qifa_propvalue_id.errTip = proxy!.$t("goods_attribute.merge_error")
					isError = true
				}
				if(titem.cc_propvalue_id == ""){
					tableConfig.tableData[i].cc_propvalue_id.errTip = proxy!.$t("goods_attribute.merge_error")
					isError = true
				}
			} else if (excludeTableData.some(item => item?.qifa_propvalue_id?.value === titem?.qifa_propvalue_id && tem?.cc_propvalue_id?.value === titem?.cc_propvalue_id)) {
				tableConfig.tableData[i].qifa_propvalue_id.errTip = proxy!.$t(
					"goods_attribute.merge_hint"
				);
				tableConfig.tableData[i].cc_propvalue_id.errTip = proxy!.$t(
					"goods_attribute.merge_hint"
				);
				isError = true
			} else if(excludeTableData.some(item => item?.merge_propvalue_ru?.value === titem?.merge_propvalue_ru)){
				tableConfig.tableData[i].merge_propvalue_ru.errTip = proxy!.$t(
					"goods_attribute.clearance_error_cn"
				);
				isError = true
			} else if(excludeTableData.some(item => item?.merge_propvalue_cn?.value === titem?.merge_propvalue_cn)){
				tableConfig.tableData[i].merge_propvalue_cn.errTip = proxy!.$t(
					"goods_attribute.clearance_error_cn"
				);
				isError = true
			}
		}
		if(isError){
			return true
		} else {
			return false
		}
	}
	const initError = () =>{
		tableConfig.tableData.map((item,idx)=>{
			tableConfig.tableData[idx].merge_propvalue_ru.errTip = "";
			tableConfig.tableData[idx].merge_propvalue_cn.errTip = "";
			tableConfig.tableData[idx].qifa_propvalue_id.errTip = ""
			tableConfig.tableData[idx].cc_propvalue_id.errTip = ""
		})
	}
	const submitForm = async (formEl : FormInstance | undefined,isHide:boolean) => {
		
		if (!formEl) return
		await initError()
		await formEl.validate((valid, fields) => {
			if (valid) {
				let tableDataArr = [];
				if(isShowTable.value){
					tableDataArr = editTableRef.value.submitData();
					if(tableDataArr && tableDataArr.length > 0){
						if(handleValidEditTable(tableDataArr)){
							return false;
						}
					} else {
						failMsg(proxy!.$t("goods_attribute.add_hint"))
						return false;
					}
				}
				
				let postData = {
					prop:ruleForm
				}
				if(isShowTable.value){
					postData.propvalue = tableDataArr;
				}
				if(Object.keys(newRules).length > 0){
					Object.keys(newRules).map((key) => {
					  newRules[key] = undefined;
					});
				}
				setMergeAttribute(postData).then(({ code, data,message,errors }) => {
					if (code == 2000) {
						successMsg(proxy!.$t("goods_attribute.add_success"));
						formEl.resetFields()
						tableConfig.tableData = [];
						state.refresh = true;
						if(!isHide){
							emit('close',state.refresh,ruleForm.type_id)
						}
					} else {
						if(Object.keys(errors).length !== 0){
							if(errors.form && Object.keys(errors.form).length !== 0){
								Object.assign(newRules,errors.form);
							}
							if(errors.table && errors.table.length !== 0){
								errors.table.map(item=>{
									if(tableConfig.tableData[item.index][item.key]){
										tableConfig.tableData[item.index][item.key].errTip = item.message
									}
								})
							}
						} else {
							failMsg(message)
						}
					}
				})
			} else {
				console.log('error submit!', fields)
			}
		})
	}
	onMounted(() => {
		initMsg()
		let tableHead = [{
			title: proxy!.$t("goods_allocation_merge.merge_propvalue_ru"),
			field: 'merge_propvalue_ru',
			length:100,
		}, {
			title: proxy!.$t("goods_allocation_merge.merge_propvalue_cn"),
			field: 'merge_propvalue_cn',
			length:50,
		}, {
			title: proxy!.$t("goods_allocation_merge.qifa_propvalue_id"),
			field: 'qifa_propvalue_id'
		},
		{
			title: proxy!.$t("goods_allocation_merge.cc_propvalue_id"),
			field: 'cc_propvalue_id'

		},
		{
			title: proxy!.$t("goods_attribute.sort"),
			field: 'sort'
		
		},
		]
		Object.assign(tableHeadData, tableHead);
		let headCon = {
			merge_propvalue_ru: "input",
			merge_propvalue_cn: "input",
			qifa_propvalue_id: {
				type: "select",
				options: opstionsObjs.qifaPropval
			},
			cc_propvalue_id: {
				type: "select",
				options: opstionsObjs.ccPropval
			},
			sort:"input",
		}
		Object.assign(headConfig, headCon);
		let tableDataArr = [];
		tableData.value = tableDataArr;
	})
</script>

<style type="text/css">
	@import "./addMerge.scss";
</style>